"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 发布订阅
Case Name   : gs_probackup使用opradmin用户备份发布端
Create At   : 2022-11-09
Owner       : opentestcase033
Description :
    1.在两个集群创建模式、表
    2.发布端打开增量备份开关
    3.创建发布订阅
    4.创建opradmin用户没有发布端权限
    5.远程备份发布端
    6.修改operation_mode为on
    7.再次备份
    8.清理环境
Expect      :
    1.成功
    2.成功
    3.成功
    4.成功
    5.提示错误，ERROR: query failed: ERROR:  must be system admin or
    replication role or operator admin in operation mode to run a backup
    6.成功
    7.成功
    8.成功
History     :
"""

import os
import time
import unittest
from yat.test import macro
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != Primary_SH.get_node_num(), '非1+2环境不执行')
class Pubsubclass(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f"-----{os.path.basename(__file__)} start-----")
        self.pri_userdb_pub = Node(node='PrimaryDbUser')
        self.pri_userdb_pub_std = Node(node='Standby1DbUser')
        self.pri_userdb_sub = Node(node='remote1_PrimaryDbUser')
        self.constant = Constant()
        self.commsh_pub = CommonSH('PrimaryDbUser')
        self.commsh_pub_std = CommonSH('Standby1DbUser')
        self.commsh_sub = CommonSH('remote1_PrimaryDbUser')
        self.com_pub = Common()
        self.com_sub = Common('remote1_PrimaryDbUser')
        self.schema = 's_pubsub_0215'
        self.user = 'u_pubsub_0215'
        self.tb_name1 = 't_pubsub_0215_1'
        self.tb_name2 = 't_pubsub_0215_2'
        self.subname = "sub_pubsub_0215"
        self.pubname = "pub_pubsub_0215"
        self.path = os.path.dirname(macro.DB_INSTANCE_PATH)
        self.backup_path = os.path.join(self.path, 'backup0215')
        self.remote_path = os.path.join(self.path, 'app', 'bin')
        self.remote_libpath = os.path.join(self.path, 'app', 'lib')
        self.port = str(int(self.pri_userdb_pub.db_port) + 1)
        self.wal_level = self.com_pub.show_param("wal_level")
        self.operation_mode = self.com_pub.show_param("operation_mode")
        self.enable_cbm_tracking = self.com_pub.show_param(
            "enable_cbm_tracking")
        self.user_param_pub = f'-U {self.pri_userdb_pub.db_user} ' \
                              f'-W {self.pri_userdb_pub.db_password}'
        self.user_param_sub = f'-U {self.pri_userdb_sub.db_user} ' \
                              f'-W {self.pri_userdb_sub.db_password}'
        text = '-----查询集群状态,配置白名单,发布端设置wal_level=logical-----'
        self.log.info(text)
        self.log.info('-----发布端状态-----')
        status = self.commsh_pub.get_db_cluster_status('detail')
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        self.log.info('-----订阅端状态-----')
        status = self.commsh_sub.get_db_cluster_status(
            'detail', env_path=macro.DB_ENV_PATH_REMOTE1)
        self.log.info(status)
        self.assertEqual(status.count('Normal'), 4, f'执行失败:{text}')
        guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host  replication  {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32  sha256')
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'发布端配置白名单失败:{text}')
        if 'logical' != self.wal_level:
            result = self.commsh_pub.execute_gsguc(
                'set', self.constant.GSGUC_SUCCESS_MSG, 'wal_level=logical')
            self.assertTrue(result, f'设置wal_level失败:{text}')
            restart_res = self.commsh_pub.restart_db_cluster()
            self.assertTrue(restart_res, f'重启数据库失败:{text}')
        guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host  replication  {self.pri_userdb_pub.db_user}  '
            f'{self.pri_userdb_pub.db_host}/32  sha256',
            macro.DB_ENV_PATH_REMOTE1)
        self.log.info(guc_res)
        self.assertTrue(guc_res, f'订阅端配置白名单失败:{text}')

    def test_pub_sub(self):
        text = "--step1:在两个集群创建表空间,数据表 expect:成功--"
        self.log.info(text)
        sql = f"drop schema if exists {self.schema} cascade;" \
              f"create schema {self.schema};" \
              f"drop table if exists {self.schema}.{self.tb_name1};" \
              f"drop table if exists {self.tb_name2};" \
              f"create table {self.schema}.{self.tb_name1}(" \
              f"id1 int primary key,id2 int,id3 int);" \
              f"create table {self.tb_name2}(" \
              f"id int primary key constraint id_nn not null," \
              f"use_filename varchar2(20),filename varchar2(255)," \
              f"text varchar2(2000)) partition by range(id)(" \
              f"partition p1 values less than(30)," \
              f"partition P2 values less than(60)," \
              f"partition P3 values less than(90)," \
              f"partition P4 values less than(MAXVALUE));"
        pub_result = self.commsh_pub.execut_db_sql(
            sql, sql_type=self.user_param_pub)
        self.log.info(pub_result)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG, pub_result,
                      f"执行失败:{text}")
        self.assertEqual(pub_result.count(self.constant.TABLE_CREATE_SUCCESS),
                         4, f"执行失败:{text}")
        sub_result = self.commsh_sub.execut_db_sql(
            sql, self.user_param_sub, None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_result)
        self.assertIn(self.constant.CREATE_SCHEMA_SUCCESS_MSG, sub_result,
                      f"执行失败:{text}")
        self.assertEqual(sub_result.count(self.constant.TABLE_CREATE_SUCCESS),
                         4, f"执行失败:{text}")

        text = "-----step2:发布端打开增量备份开关;expect:成功-----"
        self.log.info(text)
        result = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            'enable_cbm_tracking=on')
        self.log.info(result)
        self.assertTrue(result, f"执行失败:{text}")

        text = "--step3:创建发布订阅 expect:成功--"
        self.log.info(text)
        sql_cmd = f"drop publication if exists {self.pubname};" \
                  f"create publication {self.pubname} for table " \
                  f"{self.schema}.{self.tb_name1},{self.tb_name2};"
        pub_result = self.commsh_pub.execut_db_sql(
            sql_cmd, sql_type=self.user_param_pub)
        self.log.info(pub_result)
        self.assertIn(self.constant.create_pub_succ_msg, pub_result,
                      f"执行失败:{text}")
        result = self.commsh_sub.execute_generate(
            macro.COMMON_PASSWD, env_path=macro.DB_ENV_PATH_REMOTE1)
        self.assertIn(self.constant.create_keycipher_success, result,
                      f"执行失败:{text}")
        sql_cmd = f"drop subscription if exists {self.subname};" \
                  f"create subscription {self.subname} connection " \
                  f"'host={self.pri_userdb_pub.db_host} " \
                  f"port={self.port} user={self.pri_userdb_pub.db_user} " \
                  f"dbname={self.pri_userdb_pub.db_name} " \
                  f"password={self.pri_userdb_pub.ssh_password}' " \
                  f"publication {self.pubname};"
        sub_result = self.commsh_sub.execut_db_sql(
            sql_cmd, self.user_param_sub, None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_result)
        self.assertIn(self.constant.create_sub_succ_msg, sub_result,
                      f"执行失败:{text}")

        text = "--step4:创建opradmin用户没有发布端权限;expect:成功--"
        self.log.info(text)
        sql = f"drop user if exists {self.user} cascade;" \
              f"create user {self.user} with opradmin " \
              f"identified by '{macro.COMMON_PASSWD}';"
        self.log.info(sql)
        result = self.commsh_pub.execut_db_sql(sql)
        self.log.info(result)
        self.assertIn(self.constant.CREATE_ROLE_SUCCESS_MSG, result,
                      f"执行失败:{text}")

        text = "-----step5:发布端全量备份;expect:提示错误-----"
        self.log.info(text)
        check_cmd = f'if [ -d {self.backup_path} ]; then ' \
                    f'rm -rf {self.backup_path}; fi; mkdir {self.backup_path};'
        self.log.info(check_cmd)
        result = self.pri_userdb_pub_std.sh(check_cmd).result()
        self.log.info(result)
        gs_probackup_init = self.commsh_pub_std.exec_pro_backup_init(
            self.backup_path)
        self.log.info(gs_probackup_init)
        self.assertTrue(gs_probackup_init, f"执行失败:{text}")
        other_cmd = f"--remote-proto=ssh --remote-port=22 " \
                    f"--remote-host={self.pri_userdb_pub.db_host} " \
                    f"--remote-user={self.pri_userdb_pub.ssh_user} " \
                    f"--remote-path={self.remote_path} " \
                    f"--remote-libpath={self.remote_libpath}"
        gs_probackup_add = self.commsh_pub_std.exec_pro_back_add(
            self.backup_path, 'instance', other_cmd)
        self.log.info(gs_probackup_add)
        self.assertTrue(gs_probackup_add, f"执行失败:{text}")
        gs_probackup = self.commsh_pub_std.exec_pro_backup_backup(
            self.backup_path, 'instance', 'full', self.pri_userdb_pub.db_name,
            f"-U {self.user} -W {macro.COMMON_PASSWD} {other_cmd} "
            f"--backup-pg-replslot", get_detail=True)
        self.log.info(gs_probackup)
        self.assertIn(f'ERROR: query failed: ERROR:  must be system admin '
                      f'or replication role or operator admin in operation '
                      f'mode to run a backup', gs_probackup, f"执行失败:{text}")

        text = "-----step6:修改operation_mode为on;expect:成功-----"
        self.log.info(text)
        result = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, 'operation_mode=on')
        self.log.info(result)
        self.assertTrue(result, f"执行失败:{text}")

        text = "-----step7:再次备份;expect:成功-----"
        self.log.info(text)
        gs_probackup = self.commsh_pub_std.exec_pro_backup_backup(
            self.backup_path, 'instance', 'full', self.pri_userdb_pub.db_name,
            f"-U {self.user} -W {macro.COMMON_PASSWD} {other_cmd} "
            f"--backup-pg-replslot")
        self.log.info(gs_probackup)
        self.assertTrue(gs_probackup, f"执行失败:{text}")

    def tearDown(self):
        text = "--step8:清理环境;expect:成功--"
        self.log.info(text)
        drop_sub_res = self.commsh_sub.execut_db_sql(
            f"drop subscription if exists {self.subname};",
            self.user_param_sub, None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_sub_res)
        drop_pub_res = self.commsh_pub.execut_db_sql(
            f"drop publication if exists {self.pubname};",
            sql_type=self.user_param_pub)
        self.log.info(drop_pub_res)
        sql_cmd = f"drop table if exists {self.schema}.{self.tb_name1};" \
                  f"drop table if exists {self.tb_name2};" \
                  f"drop schema if exists {self.schema} cascade;"
        drop_res0 = self.commsh_sub.execut_db_sql(
            sql_cmd, self.user_param_sub, None, macro.DB_ENV_PATH_REMOTE1)
        self.log.info(drop_res0)
        drop_res1 = self.commsh_pub.execut_db_sql(
            sql_cmd, sql_type=self.user_param_pub)
        self.log.info(drop_res1)
        guc_res = self.commsh_pub.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'wal_level={self.wal_level}')
        self.log.info(guc_res)
        guc_res1 = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'enable_cbm_tracking={self.enable_cbm_tracking}')
        self.log.info(guc_res1)
        guc_res2 = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'operation_mode={self.operation_mode}')
        self.log.info(guc_res2)
        pub_guc_res = self.commsh_pub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, '',
            f'host  replication  {self.pri_userdb_sub.db_user}  '
            f'{self.pri_userdb_sub.db_host}/32')
        self.log.info(pub_guc_res)
        restart_res = self.commsh_pub.restart_db_cluster()
        sub_guc_res = self.commsh_sub.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG, '',
            'all', False, False, macro.DB_INSTANCE_PATH_REMOTE1,
            f'host  replication  {self.pri_userdb_pub.db_user}  '
            f'{self.pri_userdb_pub.db_host}/32', macro.DB_ENV_PATH_REMOTE1)
        self.log.info(sub_guc_res)
        cmd = f"rm -rf {self.backup_path};"
        self.log.info(cmd)
        sh_result1 = self.pri_userdb_pub_std.sh(cmd).result()
        self.log.info(sh_result1)
        self.assertIn(self.constant.drop_sub_succ_msg, drop_sub_res,
                      f'删除订阅失败:{text}')
        self.assertIn(self.constant.drop_pub_succ_msg, drop_pub_res,
                      f'删除发布失败:{text}')
        self.assertEqual(drop_res0.count(self.constant.DROP_TABLE_SUCCESS), 2,
                         f'删除订阅端表失败:{text}')
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, drop_res0,
                      f"删除订阅端模式失败:{text}")
        self.assertEqual(drop_res1.count(self.constant.DROP_TABLE_SUCCESS), 2,
                         f'删除发布端表失败:{text}')
        self.assertIn(self.constant.DROP_SCHEMA_SUCCESS_MSG, drop_res1,
                      f"删除发布端模式失败:{text}")
        self.assertTrue(guc_res and guc_res1 and guc_res2, f'执行失败:{text}')
        self.assertTrue(restart_res, f'发布端重启数据库失败:{text}')
        self.assertTrue(pub_guc_res, f'发布端删除白名单失败:{text}')
        self.assertTrue(sub_guc_res, f'订阅端删除白名单失败:{text}')
        self.log.info(f"-----{os.path.basename(__file__)} end-----")
